package org.budo.netty.servlet.server.connector.smart;

import java.io.IOException;

import javax.servlet.DispatcherType;
import javax.servlet.ServletException;

import org.budo.netty.servlet.server.connector.AbstractHttpConnector;
import org.budo.netty.servlet.server.handler.BudoServletHandler;
import org.budo.netty.servlet.server.handler.servlet.BudoServletRequest;
import org.budo.netty.servlet.server.handler.servlet.BudoServletResponse;
import org.budo.netty.servlet.server.handler.servlet.DefaultBudoServletResponse;
import org.smartboot.http.HttpBootstrap;
import org.smartboot.http.HttpRequest;
import org.smartboot.http.HttpResponse;
import org.smartboot.http.server.handle.HttpHandle;

/**
 * @author lmw
 */
public class SmartHttpConnector extends AbstractHttpConnector {
    public SmartHttpConnector(Integer port) {
        this.setPort(port);
    }

    @Override
    public void start(final BudoServletHandler servletHandler) {
        HttpBootstrap bootstrap = new HttpBootstrap();
        // 普通http请求
        bootstrap.pipeline().next(new HttpHandle() {
            @Override
            public void doHandle(HttpRequest request, HttpResponse response) throws IOException {
                BudoServletRequest req = new SmartHttpRequest(request, servletHandler, SmartHttpConnector.this);
                BudoServletResponse resp = new DefaultBudoServletResponse();

                try {
                    servletHandler.handleRequest(req, resp, DispatcherType.REQUEST);
                } catch (ServletException e) {
                    throw new RuntimeException(e);
                }

                for (String name : resp.getHeaderNames()) {
                    response.setHeader(name, resp.getHeader(name));
                }

                response.write(resp.getOutputStreamByteArray());
            }
        });
        bootstrap.setPort(this.getPort()).start();
    }
}